"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""
from flask import request
from flask_restx import Resource, Namespace, fields

from do.plan_do import PlanDo
from server import api
from service.plan_service import PlanService

plan_ns = Namespace("plan", description="测试计划管理")

plan_service = PlanService()


@plan_ns.route("")
class PlanController(Resource):
    plan_get_parser = api.parser()
    plan_get_parser.add_argument("id", type=int, location="args")

    @plan_ns.expect(plan_get_parser)
    def get(self):
        """
        测试计划的查找
        :return:
        """
        id = request.args.get("id")
        print(id)
        if id:
            data = plan_service.get(id)
            if data:
                datas = [plan_service.get(id).as_dict()]
                return {"code": 0, "msg": "data success get", "data": datas}
            else:
                return {"code": 40004, "msg": "data is not exists"}

        else:
            datas = [plan.as_dict() for plan in plan_service.list()]
            return {"code": 0, "msg": "data success get", "data": datas}

    plan_post_model = plan_ns.model("plan_post_model", {
        "name": fields.String,
        "testcase_ids": fields.List(fields.Integer)
    })

    @plan_ns.expect(plan_post_model)
    def post(self):
        """
        测试计划的新增
        :return:
        """
        data = request.json
        # {a=1,b=2}   a=1,b=2
        testcase_id_list = data.pop("testcase_ids")
        plan = PlanDo(**data)
        plan_id = plan_service.save(testcase_id_list, plan)
        if plan_id:
            return {"code": 0, "msg": f"{plan_id} success add"}
        else:
            return {"code": 40001, "msg": "case is exists"}

    plan_delete_parser = api.parser()
    plan_delete_parser.add_argument("id", type=int, location="json", required=True)

    @plan_ns.expect(plan_delete_parser)
    def delete(self):
        """
        测试计划的删除
        :return:
        """
        data = request.json
        plan_id = data.get("id")
        id = plan_service.delete(plan_id)
        if id:
            return {"code": 0, "msg": f"{id} success delete"}
        else:
            return {"code": 40002, "msg": "case is not exists"}